package com.woniuxy.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 马宇航
 * @Description: 死信交换机配置
 * @DateTime: 22/10/20/0020 14:19
 * @Component: 成都蜗牛学苑
 **/
@Configuration
public class DeadConfig {
    //********************* 正常的交换机与队列的配置 ******************************
    //正常的交换机
    @Bean
    public DirectExchange directExchangeForDead(){
        return new DirectExchange("forDeathDirectExchange");
    }
    //正常的队列,设置第一个有过期ttl时间配置的队列，还需要有一个如果超时后，怎么办的配置？ forDeathQueue1
    @Bean
    public Queue directQueueForDead1(){
        HashMap<String, Object> ttlArgs = new HashMap<>();
        ttlArgs.put("x-message-ttl",6*1000);
        ttlArgs.putAll(deadArgs());
        return new Queue("forDeathQueue1",true,true,false,ttlArgs);
    }
    //配置有长度限制的队列forDeathQueue2
    @Bean
    public Queue directQueueForDead2(){
        HashMap<String, Object> maxLength = new HashMap<>();
        maxLength.put("x-max-length",5);
        maxLength.putAll(deadArgs());
        return new Queue("forDeathQueue2",true,true,false,maxLength);
    }
    @Bean
    public Binding bindingForDeadQueue1(){
        return BindingBuilder.bind(directQueueForDead1()).to(directExchangeForDead()).with("ttl");
    }
    @Bean
    public Binding bindingForDeadQueue2(){
        return BindingBuilder.bind(directQueueForDead2()).to(directExchangeForDead()).with("maxlength");
    }
    //********************* 正常的交换机与队列的配置 ******************************
    //********************* 死信交换机与队列的配置 ******************************
     @Bean
     public DirectExchange deadExchange(){
         return new DirectExchange("deadExchange");
     }
    @Bean
    public Queue deadQueue(){
        return new Queue("deadQueue",true,true,false);
    }
    @Bean
    public Binding bindingDead(){
        return BindingBuilder.bind(deadQueue()).to(deadExchange()).with("deadMessage");
    }
    //********************* 死信交换机与队列的配置 ******************************
     //这个方法是给正常的队列使用的，叫做 兜底参数：告诉队列，如果出现问题，可以把消息发给下面配置的地方
     public Map deadArgs(){
        Map<String,Object> otherArgs = new HashMap<>();
        otherArgs.put("x-dead-letter-exchange","deadExchange");
        otherArgs.put("x-dead-letter-routing-key","deadMessage");
        return otherArgs;
     }
}
